package com.lxp.test;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import org.eclipse.paho.client.mqttv3.MqttClient;

import java.math.RoundingMode;

public class MqttDemo {
    private static final int qos = 1; //只有一次
    private static final String broker = "tcp://121.40.210.234:1883";
    private static final String clientId = "5qQ6dHFGXygwDkrvZvqu";
    private static final String PUBLISH_TOPIC = "xky/up/sub/002/1";
    //private static final String PUBLISH_TOPIC = "v1/devices/me/telemetry";
    //订阅到服务器的topic标识
    private static final String SUBSCRIBE_TOPIC = "xky/up/sub/#";

    @SneakyThrows
    public static void main(String[] args) {
        MqttClient mqttClient = MqttUtil.connectMqtt(broker, clientId, clientId, clientId);
        mqttClient.subscribe(SUBSCRIBE_TOPIC, qos);

        for (int i = 0; i < 10; i++) {
            Thread.sleep(2000L);
            double aDouble = RandomUtil.randomDouble(0.0, 500.0, 2, RoundingMode.DOWN);
            double v = RandomUtil.randomDouble(0.0, 100.0, 2, RoundingMode.DOWN);
            double v1 = RandomUtil.randomDouble(0.0, 100.0, 2, RoundingMode.DOWN);
            JSONObject json1 = JSONUtil.createObj().set("method", aDouble).set("shidu", v).set("wendu", v1);
            MqttUtil.sendData(mqttClient, PUBLISH_TOPIC, json1.toString());
        }
        //mqttClient.disconnect();
    }
}
